﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Data;
using DBUtility;
/*************************************************************************************

     用户登录  liudan add
  
*************************************************************************************/
namespace DAL
{
    public class UserDAL
    {
        /// <summary>
        /// 登录
        /// </summary>
        public string login(string name,string password,out string id)
        {
            string lb_return = "0";
            id = "";

            DataTable dt = new DataTable();
            StringBuilder commandText = new StringBuilder();

            string md5 = GetMD5Hash(password);
            int Num = 0;
            
            commandText.Append(" select COUNT(*) ");
            commandText.Append(" from sys_master ");
            commandText.Append(" where NAME='" + name + "' ");
            commandText.Append(" and PASSWORD='" + md5 + "'");
          
            try
            {
                DbHelperSQL.connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
                Object obj = DbHelperSQL.GetSingle(commandText.ToString());
                if (!Object.Equals(obj, null))
                {
                    Num = int.Parse(obj.ToString());
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (Num > 0) { lb_return = "1"; id = GetId(name, md5); }

            return lb_return;
        }

        public static string GetMD5Hash(String Password)
        {
            var md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(Password)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }

        public string GetId(string name, string md5) 
        {
            string id = "";
            DataTable dt = new DataTable();
            StringBuilder commandText = new StringBuilder();

            commandText.Append(" select MAX(ID) ");
            commandText.Append(" from sys_master ");
            commandText.Append(" where NAME='" + name + "' ");
            commandText.Append(" and PASSWORD='" + md5 + "'");
            try
            {
                DbHelperSQL.connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
                Object obj = DbHelperSQL.GetSingle(commandText.ToString());
                if (!Object.Equals(obj, null))
                {
                    id = obj.ToString();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            } 
            return id;
        }


    }
}
